<?php
namespace app\service;

use Qcloud\Cos\Client;
use Qcloud\Cos\Exception\CosException;

class OssService
{
    private $secretId = 'AKIDy9caOyMXTCGD0XyB9wtgEXr04xcBYicO';
    private $secretKey = 'c09Xknb9TZR5X8nNrCrLdhW6SZSL4as6';
    private $region = 'ap-shanghai'; // 腾讯云COS区域
    private $internalEndpoint = 'cos.ap-shanghai.myqcloud.com'; // 内网endpoint
    private $publicEndpoint = 'cos.ap-shanghai.myqcloud.com'; // 公网endpoint
    private $bucket = 'share-1259268558'; // 默认bucket
    private $client;

    public function __construct($bucket = '')
    {
        $this->bucket = $bucket ?: $this->bucket;
        
        // 使用内网endpoint进行上传操作
        $this->client = new Client([
            'region' => $this->region,
            'endpoint' => $this->internalEndpoint,
            'credentials' => [
                'secretId' => $this->secretId,
                'secretKey' => $this->secretKey,
            ],
        ]);
    }

    /**
     * 上传文件到COS
     * @param string $object COS对象名（含路径）
     * @param string $filePath 本地文件路径
     * @return string 上传后的COS文件URL
     * @throws CosException
     */
    public function putObject($object, $filePath)
    {
        $this->client->putObject([
            'Bucket' => $this->bucket,
            'Key' => $object,
            'Body' => fopen($filePath, 'rb'),
        ]);
        
        // 返回公网访问URL
        return "https://{$this->bucket}.cos.{$this->region}.myqcloud.com/{$object}";
    }

    /**
     * 获取COS文件内容
     * @param string $object COS对象名（含路径）
     * @return string 文件内容
     * @throws CosException
     */
    public function getObject($object)
    {
        $result = $this->client->getObject([
            'Bucket' => $this->bucket,
            'Key' => $object,
        ]);
        
        return $result['Body']->getContents();
    }
} 